package com.im.foodorderingsystem.task;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;

import com.im.foodorderingsystem.Utility;
import com.im.foodorderingsystem.db.FOSDB;

public class SyncTask extends AsyncTask<String, String, String>{

	Context context;
	
	public SyncTask(Context context) {
		this.context=context;
	}
	
	@Override
	protected String doInBackground(String... arg0) {
		
		String URL=Utility.syncUrl;
		
		String result = null;
		HttpGetRequest httpgetrequest=new HttpGetRequest(URL);
		result=httpgetrequest.send();
		
		return result;
	}
	
	@Override
	protected void onPostExecute(String result) {
		try {
			System.out.println(result);
			
			JSONObject jsonObj = new JSONObject(result);
			JSONArray categoryArray= jsonObj.getJSONArray("category");
			
			FOSDB fosdb=new FOSDB(context);
			SQLiteDatabase db=fosdb.getReadableDatabase();
			
			for(int i=0; i<categoryArray.length(); i++){
				JSONObject tempCategory = categoryArray.getJSONObject(i);
				System.out.println(tempCategory.getString("name"));
				
				int categoryID=Integer.parseInt(tempCategory.getString("category_id"));
				
				String sqlSelect="select * from '"+FOSDB.CATEGORY_TABLE_NAME+"' "
						+ "where category_id="+categoryID;
				Cursor cursor=db.rawQuery(sqlSelect,null);
				if (cursor != null) {
					if (cursor.moveToFirst()) {
						System.out.println(categoryID+"found");
					}else{						
						String sqlInsert="insert into '"+FOSDB.CATEGORY_TABLE_NAME+"' "
								+ "('category_id,')";
						
						System.out.println(categoryID+"not found");
					}
				}
				//System.out.println("execute");
			}
			
			//System.out.println("???"+sys.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
